<?php
namespace app\common\controller;
use \think\Controller;
use \think\Loader;
use \think\Db;
use \think\Config;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
class Base extends Controller {
    protected $wheresql = '';
    protected $data = [];
    protected $option = [
        // 缓存类型为File
        'type'   => 'File',
        // 缓存有效期为永久有效
        'expire' => 0,
        // 指定缓存目录
        'path'   => DATA_PATH ,
    ];
    public function _initialize() {
        header("Access-Control-Allow-Origin:*");
        header('Content-Type:application/json;charset=utf8');
        header("Access-Control-Allow-Headers: Origin, X-Requested- With, Content-Type, Accept");
        $inputJSON = file_get_contents('php://input');
        $input = json_decode($inputJSON, TRUE);
        //$mall_domain = \app\common\model\Base::get_domain_set('mall_domain',1);
//        if(!empty($input['token'])){
//            //验证token是否存在，存在则更新有效时间
//            $this->data = $input;
//            // $web = \app\system\model\Login::get_login_token($input['token']);
//            // if(!empty($web)){
//            //     $this->data = $input;
//            // }else{
//            //     print_r(json_encode(api_return(-11406)));exit;
//            // }
//        }elseif(!empty($input['domain'])){
//            if($input['domain']=='www.zzqd.com'){
//                cache($input['domain'],$input['domain'],get_cache_path(false));
//                $input['web_id'] =!empty($domain['web_id'])?$domain['web_id']:0;
//                $this->data = $input;
//            }else{
//                print_r(json_encode(api_return(-13002)));exit;
//            }
//
//        }else{
//            print_r(json_encode(api_return(-13002)));exit;
//        }
    }

    function getParams() {
        $inputJSON = file_get_contents('php://input');
        return json_decode($inputJSON, TRUE) ?? [];
    }

    /**
     * 上传文件
     * @param	string			$folder		保存的文件夹
     * @param	array			$config		上传配置
     */
    public function uploadFile($folder='',$config=[]){
        $config['size'] = $config['size']??10240000;
        $config['ext'] = $config['ext']??'png,jpg,jpeg,gif,bmp,xls';
        $result = [];
        foreach($_FILES as $key=>$value){
            $files = request()->file($key);//获取上传的文件
            if(is_array($files)){
                foreach($files as $one){
                    $result[$key][] = $this->moveFile($folder,$one,$config);
                }
            }else if($files){
                $result[$key] = $this->moveFile($folder,$files,$config);
            }
        }
        return $result;
    }
    public function moveFile($folder='',$one=[],$config=[]){
        $return = [];
        $info = $one->validate($config)->move(ROOT_PATH.'public'.DS.'upload'.DS.$folder);
        if(!$info){
            if(request()->isAjax()){
                $return['msg'] = $one->getError();
                return_json($return);
            }
            else{
                $this->showMessage($one->getError(),0);
            }
        }
        else{
            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
            $return['url'] = DS.'upload'.DS.$folder.DS.$info->getSaveName();
        }
        return $return;
    }
    //上传--调用方法---
    /**
     * @param array $config 文件大小与类型的配置
     * @param string $folder 文件夹
     * @return mixed
     */
    public function uploadfile_qiniu($config=[],$folder=''){
        $folder = $folder?$folder.'/':'yaliapi/';
        $config = array(
            'size' =>   $config['size']??1048576,//默认1M
            'ext'  =>   $config['ext']??'png,jpg,jpeg,gif,bmp',
        );
        foreach($_FILES as $key=>$val){
            $file = request()->file($key);
            //区分单文件与多文件
            if(is_array($file)){
                //先验证
                foreach($file as $k =>$v){
                    $v->validate($config)->check();
                    $error_msg = $v->getError();
                    //再上传
                    if($error_msg){
                        return show_result(0,$error_msg);
                    }else{
                        $file_qiniu = $this->qiniu($v,$folder);
                        if($file_qiniu['status']==1){
                            $file_url['url'] = $file_qiniu['data'];
                            $file_info[$k] = array_merge($v->getInfo(),$file_url);
                        }else{
                            return show_result(0,$file_qiniu['msg']);
                        }
                    }
                }
                return show_result(1,'上传成功',$file_info,true);
            }else{
                $file->validate($config)->check();
                $error_msg = $file->getError();
                //再上传
                if($error_msg){
                    return show_result(0,$error_msg);
                }else{
                    $file_qiniu = $this->qiniu($file,$folder);
                    if($file_qiniu['status']==1){
                        $file_url['url'] = $file_qiniu['data'];
                        return show_result(1,'上传成功',array_merge($val,$file_url),true);
                    }else{
                        return show_result(0,$file_qiniu['msg']);
                    }
                }
            }
        }
    }
    //七牛上传调用插件--
    public function qiniu($file,$folder=''){
        $qiniu_config = config('qiniu');
        require_once VENDOR_PATH.'/qiniu/php-sdk/autoload.php';

        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = $qiniu_config['ACCESSKEY'];
        $secretKey = $qiniu_config['SECRETKEY'];
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);

        // 要上传的空间
        $bucket =  $qiniu_config['BUCKET'];

        // 生成上传 Token
        $token = $auth->uploadToken($bucket);

        // 要上传文件的本地路径
        $filePath = $file->getRealPath();

        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀

        // 上传到七牛后保存的文件名
        $key = $folder.substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;

        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();

        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return array('status'=>0,'msg'=>$err,'data'=>'');
            return   $err;
        } else {
            return array('status'=>1,'msg'=>'上传成功','data'=>$qiniu_config['DOMAIN'].'/'.$key);
        }
    }
// 文件
    public function _qiniuPng($filePath,$folder='') {
        $qiniu_config = config('qiniu');
        require_once VENDOR_PATH.'/qiniu/php-sdk/autoload.php';
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = $qiniu_config['ACCESSKEY'];
        $secretKey = $qiniu_config['SECRETKEY'];
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);

        // 要上传的空间
        $bucket =  $qiniu_config['BUCKET'];

        // 生成上传 Token
        $token = $auth->uploadToken($bucket);
        $ext = "png";  //后缀

        // 上传到七牛后保存的文件名
        $key = $folder.substr(md5($filePath) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;

        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();

        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return array('status'=>0,'msg'=>$err,'data'=>'');
        } else {
            return array('status'=>1,'msg'=>'上传成功','data'=>$qiniu_config['DOMAIN'].'/'.$key);
        }
    }
    //https请求（支持GET和POST） old
    static protected function https_request($url, $data = null) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        $output_json = json_decode($output);
        return $output_json;
    }
}
